#include "net/tcp_server.hpp"
#include "base/logger.h"
#include <iostream>

using namespace easyasio::net;

int main(int argc, char* argv[])
{

    if (argc != 3)
    {
        printf("usage: ./server port no_delay[1 | 0]\n");
        exit(-1);
    }
    try
    {
        bool is_no_delay = atoi(argv[2]) ? true : false;
         
        std::shared_ptr<TcpServer> s(std::make_shared<TcpServer>("0.0.0.0", argv[1], 1));
    	s->setMessageCallback([](const TcpConnectionPtr& conn, Buffer* buf)
    	{
    		//std::cout << std::string(buf->peek(), buf->readableBytes()) << std::endl;
    		conn->send(std::string(buf->peek(), buf->readableBytes()));
    		buf->retrieveAll();
    	} );

    	s->setConnectionCallback([is_no_delay](const TcpConnectionPtr& conn)
    	{
    		std::cout << "new connection" << std::endl;
            conn->setTcpNoDelay(is_no_delay);
    	});

    	s->run();

    	int a;
    	std::cin >> a;
    }
    catch (asio::system_error& e)
    { 
        LOG_ERROR("{}", e.what());
    }
    catch (...)
    {
        LOG_ERROR("unknow error");
    }

    return 0;
}